package me.xinping.libs.recording

import android.media.MediaRecorder
import me.xinping.libs.utils.ContextUtils
import me.xinping.libs.utils.CountTimer

/**
 * 录音/播放管理.
 * <p>
 * Date 2018/12/4
 * @author fanxinping_cd@keruyun.com
 */
class RecorderManager private constructor() {

    private var recordingListener: OnRecordingListener? = null
    private val recorder: MediaRecorder = MediaRecorder()
    private val countTimer: CountTimer = CountTimer()


    private fun initRecorder() {
        recorder.setAudioSource(AUDIO_INPUT)
        recorder.setOutputFormat(OUTPUT_FORMAT)
        recorder.setAudioEncoder(AUDIO_ENCODER)
        recorder.setAudioChannels(AUDIO_CHANNEL)
        recorder.setAudioSamplingRate(AUDIO_SAMPLE_RATE)
        recorder.setAudioEncodingBitRate(AUDIO_ENCODING_RATE)
    }


    fun startRecording(filePath: String, listener: OnRecordingListener) {
        if (filePath.isEmpty()) {
            throw IllegalArgumentException("input file is empty,please check!!!")
        }
        initRecorder()
        recorder.setOutputFile(filePath)
        recordingListener = listener
        recorder.prepare()
        recorder.start()
        countTimer.start {
            ContextUtils.runOnUIThread {
                recordingListener?.onProgress(it)
            }
        }
        recordingListener?.onStart()

    }

    fun stopRecording() {
        recorder.stop()
        recorder.reset()
        recordingListener?.onStop()
        countTimer.stop()
    }

    fun releaseRecoder() {
        recorder.release()
    }

    interface OnRecordingListener {
        /**
         * 开始录音
         */
        fun onStart()

        /**
         * 录音结束
         */
        fun onStop()

        /**
         * 录音时长，单位：秒
         */
        fun onProgress(seconds: Int)
    }

    companion object {
        val instance: RecorderManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            RecorderManager()
        }

        /**
         * 采样率，只有44100Hz是所有设备都支持的。其他22050、16000和11025只能在某些设备上使用。
         */
        private const val AUDIO_SAMPLE_RATE = 44100
        /**
         * 编码率
         */
        private const val AUDIO_ENCODING_RATE = 192000
        /**
         * 麦克风输入
         */
        private const val AUDIO_INPUT = MediaRecorder.AudioSource.MIC
        /**
         * 单声道，所有设备支持
         */
        private const val AUDIO_CHANNEL = 1
        /**
         * 编码器
         */
        private const val AUDIO_ENCODER = MediaRecorder.AudioEncoder.AMR_WB
        /**
         * 输出格式
         */
        private const val OUTPUT_FORMAT = MediaRecorder.OutputFormat.AMR_WB

    }
}